package net.yebaihe.wc;

import java.util.HashMap;

import net.yebaihe.wc.DataMan.MSGTYPE;

import com.mobclick.android.MobclickAgent;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public abstract class StateMachine extends Activity implements StateMachineInterface{

	public static final int NOTIFY_LEFT_SESSION = 10;
	LinearLayout topbar;
	private View client;
	ImageView imglevel2;
	LinearLayout level2;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWCAppContext().init();
        Log.d("myown", this.getClass().getName());
        FrameLayout layout=new FrameLayout(this);
        LinearLayout main=new LinearLayout(this);
        main.setOrientation(LinearLayout.VERTICAL);
        if (this.getClass()==Index.class){
        	main.setBackgroundColor(0xFFf1f4f9);
        }
        else if(this.getClass()==NearBy.class){
        	main.setBackgroundColor(0xFFFFFFFF);      	
        }
        else{
        	main.setBackgroundResource(R.drawable.bg_1);
        }
        topbar=(LinearLayout) View.inflate(this, R.layout.topbar, null);
        updateTopBar();
        client=View.inflate(this, getLayoutRes(), null);
        LinearLayout.LayoutParams p=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT);
        main.addView(topbar);
        main.addView(client,p);
        layout.addView(main,new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
        
        level2=new LinearLayout(this);
        imglevel2=new ImageView(this);
        level2.setGravity(Gravity.CENTER);
        level2.addView(imglevel2,new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
        layout.addView(level2);
        level2.setVisibility(View.GONE);
        level2.setBackgroundColor(0x88c8c8c8);
        level2.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				level2.setVisibility(View.GONE);
			}
        });
        
        setContentView(layout);
        prepareClient(client);
        if (this.getWCAppContext().email.length()>0) DataMan.get(this).checkNotifies();

    }
    
    protected void changeToActivity(@SuppressWarnings("rawtypes") Class target){
		Intent intent=new Intent(this,target);
		intent.putExtra("lasttitle", getTopbarTitle());
		if (target==Dishes.class){
			intent.putExtra("restaurant", getWCAppContext().restaurant);
		}
		else if (target==ShowSessionDetail.class){
			intent.putExtra("sessionid", getWCAppContext().sessionid);
		}
		else if (target==SNS.class){
			intent.putExtra("sessionid", getWCAppContext().sessionid);
		}
		startActivity(intent);
		if (target==Login.class){
			overridePendingTransition(R.anim.down_in,R.anim.down_out); 
		}
    }
    
    protected void updateTopBar() {
    	TextView txtTitle=(TextView) topbar.findViewById(R.id.txtTitle);
    	txtTitle.setText(getMost(getTopbarTitle(),5));
    	txtTitle.setTextColor(0xFFFFFFFF);
    	
    	Button txtLeft=(Button)topbar.findViewById(R.id.btnleft);
    	TextView txtMessage=(TextView)topbar.findViewById(R.id.txtMessage);
    	txtMessage.setText("");
    	String lastTitle=getIntent().getStringExtra("lasttitle");
    	if ((lastTitle!=null) && (lastTitle.length()>0)){
    		txtLeft.setText(getMost(lastTitle,3));
    		txtLeft.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View arg0) {
					goback();
				}
    		});
    	}
    	else{
    		txtLeft.setText(getWCAppContext().city);
    		txtLeft.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) {
					changeToActivity(Cities.class);
				}
    		});
    	}
    	
    	Button btnRight=(Button)topbar.findViewById(R.id.btnRight);
    	if (getWCAppContext().email.length()>0){
    		if (getWCAppContext().notifications==0){
        		btnRight.setBackgroundResource(R.drawable.p_mail);
    	   		btnRight.setText(""+getWCAppContext().notifications);
    	   		//btnRight.setEnabled(false);
    		}
    		else{
    	   		btnRight.setEnabled(true);
        		btnRight.setBackgroundResource(R.drawable.p_mail);
    	   		btnRight.setText(""+getWCAppContext().notifications);
    		}
    		btnRight.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) {
					if (StateMachine.this instanceof Notifications){
						finish();
					}
					else{
						changeToActivity(Notifications.class);
					}
				}
    		});
     	}
    	else{
	   		btnRight.setEnabled(true);
    		btnRight.setBackgroundResource(R.drawable.b_logd);
	   		btnRight.setText("");
    		btnRight.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) {
					changeToActivity(Login.class);
				}
    		});
    	}
    	
    	
    	txtLeft.setTextColor(0xFFFFFFFF);
    	LinearLayout bg=(LinearLayout)topbar.findViewById(R.id.layoutbg);
    	
    	if (this.getClass()==Login.class) {
        	bg.setBackgroundResource(R.drawable.bg_1top);
        	txtTitle.setTextColor(0xFF76797e);
        	txtLeft.setTextColor(0xFF76797e);
    		btnRight.setVisibility(View.INVISIBLE);
    	}
    	else{
        	bg.setBackgroundResource(R.drawable.bg_2top);
    	}
	}

	private CharSequence getMost(String lastTitle, int i) {
		if (lastTitle.length()>i){
			return lastTitle.substring(0, i)+"...";
		}
		return lastTitle;
	}

	protected void showBigImage(String path) {
		imglevel2.setImageBitmap(BitmapFactory.decodeFile(path));
		level2.setVisibility(View.VISIBLE);
		Animation am1 = new AlphaAnimation ( 0, 1 );
		am1. setDuration ( 1000 );
		Animation am2=new ScaleAnimation(0, 1, 0, 1);
		am2. setDuration ( 1000 );
		AnimationSet am = new AnimationSet ( false );
		am.addAnimation(am1);
		am.addAnimation(am2);
		level2.startAnimation(am);
	}    
    
	private String getCurrentCity() {
		WCApp app=(WCApp)this.getApplicationContext();
		if (app.city.length()<=0){
			app.city="北京";
		}
		return app.city;
	}

	protected void checkLeftSession() {
		if (getWCAppContext().email.length()<=0) return;
		UserInfoData userinfo = MyHelper.get(this).getCurrUserInfoData(getWCAppContext().email);
		SQLiteDatabase db = MyHelper.get(this).getReadableDatabase();
		SQLiteDatabase wdb = MyHelper.get(this).getWritableDatabase();
		Cursor c=db.rawQuery("select * from sessions where fromuid="+userinfo._id+" and state=1", null);
		if (c.moveToLast()){
			Cursor n=db.rawQuery("select * from notifications where type="+NOTIFY_LEFT_SESSION+" and userdata='"+c.getLong(0)+"'", null);
			if (n.getCount()<=0){
				Cursor r=db.rawQuery("select * from restaurants where _id="+c.getLong(4), null);
				r.moveToFirst();
				MyHelper.get(this).insertNotify(userinfo._id, userinfo._id, "您在"+r.getString(1)+"的点餐未完成", NOTIFY_LEFT_SESSION, c.getLong(0)+"");
				r.close();
			}
			else{
				Cursor r=db.rawQuery("select * from restaurants where _id="+c.getLong(4), null);
				r.moveToFirst();
				ContentValues values=new ContentValues();
				values.put("message","您在"+r.getString(1)+"的点餐未完成");
				values.put("done", 0);
				wdb.update("notifications", values, "type="+NOTIFY_LEFT_SESSION+" and userdata='"+c.getLong(0)+"'", null);
				r.close();
			}
			n.close();
		}
		else{
			wdb.delete("notifications", "type="+NOTIFY_LEFT_SESSION+" and touid="+userinfo._id, null);
		}
		c.close();
		db.close();
		wdb.close();
	}		
	
	protected boolean checkLogin(boolean redirect) {
		if (this.getWCAppContext().email.length()<=0){
			if (redirect){
				changeToActivity(Login.class);
			}
			return false;
		}
		return true;
	}	
	
	protected void goback() {
		super.onBackPressed();
	}

	protected abstract String getTopbarTitle();
	protected abstract void prepareClient(View client);
    protected abstract int getLayoutRes();
	protected WCApp getWCAppContext() {
		return (WCApp)this.getApplicationContext();
	}

	public void HandleMessage(MSGTYPE msgtype, boolean ret, HashMap<String, String> params){
		switch (msgtype){
		case CITY_CHANGE:
		{
			this.updateTopBar();
		}
			break;
		case CHECK_NOTIFICATIONS:
		{
			UserInfoData userdata = MyHelper.get(this).getCurrUserInfoData(getWCAppContext().email);
			if (userdata!=null){
				SQLiteDatabase db = MyHelper.get(this).getReadableDatabase();
				if (db!=null){
					Cursor c=db.rawQuery( 
							"SELECT count(*) FROM notifications WHERE touid="+userdata._id+" and done=0", null);
					if (c.moveToFirst()){
						getWCAppContext().notifications=c.getInt(0);
						this.updateTopBar();
					}
					c.close();
					db.close();
				}
			}
		}
			break;
		}
	}

	
	public void onResume() {
	    super.onResume();
	    MobclickAgent.onResume(this);
        checkLeftSession();
        if (this.getWCAppContext().email.length()>0) DataMan.get(this).checkNotifies();
        getWCAppContext().curStateMachine=this;
	}
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
        getWCAppContext().curStateMachine=null;
	}

}